<template>
  <div>
    <div class="main">
      <div class="overview">班级平均年龄: {{ avgAge }}</div>
      <DeleteButtons
        :selectedStudents="searchStudentArr.filter(item => item.seleted)"
        :studentArr="studentArr"
        @add="addStudent"
        @deleteSelected="delSelectedStudents"
      >
        <template #addButtonContent>
          添加学生
        </template>
        <template #deleteButtonContent>
          删除选中学生
        </template>
      </DeleteButtons>

      <SearchBar
        :initialKeyword="keyword"
        :studentArr="studentArr"
        @search="onSearch"
      >
        <template #buttonContent>
          搜索
        </template>
      </SearchBar>

      <table class="studentTable">
        <thead>
          <tr>
            <th>
              <input
                v-model="isAllSelected"
                @change="changeSelectedAll"
                type="checkbox"
                class="selectAll"
              />
            </th>
            <th>ID</th>
            <th>Name</th>
            <th>Gender</th>
            <th>Hobbies</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Age</th>
            <th>Created At</th>
            <th>Updated At</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in searchStudentArr" :key="item.id">
            <td>
              <input
                @change="changeSeletedItem"
                v-model="item.seleted"
                type="checkbox"
                class="selectAll"
              />
            </td>
            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.gender }}</td>
            <td>{{ item.hobbies }}</td>
            <td>{{ item.email }}</td>
            <td>{{ item.phone }}</td>
            <td>{{ item.age }}</td>
            <td>{{ item.create_at }}</td>
            <td>{{ item.update_at }}</td>
            <td>
              <button @click="editStuInfo(item)" class="editBtn" type="button">修改</button>
              <button @click="delStuInfo(item)" class="deleteBtn" type="button">删除</button>
            </td>
          </tr>
        </tbody>
      </table>

      <AddStudentModal
        :isShow="isShowModel"
        :title="modelInfo.title"
        :student="stuFormData"
        :type="'add'"
        @close="closeModel"
        @save="onSave"
      >
        <template #formContent>
          <input v-model="stuFormData.id" type="hidden" class="studentIdToEdit" />

          <label for="studentName">Name</label>
          <input v-model="stuFormData.name" type="text" name="name" class="studentName" required />

          <label for="studentGender">Gender</label>
          <select v-model="stuFormData.gender" name="gender" class="studentGender" required>
            <option value="Male">Male</option>
            <option value="Female">Female</option>
          </select>

          <label for="studentHobbies">Hobbies</label>
          <input v-model="stuFormData.hobbies" type="text" name="hobbies" class="studentHobbies" required />

          <label for="studentEmail">Email</label>
          <input v-model="stuFormData.email" type="email" name="email" class="studentEmail" required />

          <label for="studentPhone">Phone</label>
          <input v-model="stuFormData.phone" type="text" name="phone" class="studentPhone" required />

          <label for="studentAge">Age</label>
          <input v-model="stuFormData.age" type="number" name="age" class="studentAge" required />
        </template>
      </AddStudentModal>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { uniqueId, cloneDeep, add } from 'lodash';
import { getNowDateTime } from '@/utils';

import AddStudentModal from './components/AddStudentModal.vue';
import SearchBar from './components/SearchBar.vue';
import DeleteButtons from './components/DeleteButtons.vue';

interface IStudent {
  id: string | number;
  name: string;
  gender: string;
  hobbies: string;
  email: string;
  phone: string;
  age: number | string;
  create_at?: string;
  update_at?: string;
  seleted?: boolean;
}

// 控制模态框的显示隐藏
const isShowModel = ref(false);
// 模态框配置
const modelInfo = ref({
  type: 'add',
  title: '添加学生信息'
});
const keyword = ref('');
// 是否全选
const isAllSelected = ref(false);

const stuFormData = ref<IStudent>({
  id: '',
  age: '',
  email: '',
  gender: '',
  hobbies: '',
  name: '',
  phone: ''
});

// 从localStorage获取数据
let student = localStorage.getItem('student') as string;
const studentArr: Array<IStudent> = student ? JSON.parse(student) : [];

// 绑定数据变量(初始化)
const searchStudentArr = ref<Array<IStudent>>([]);

// 初始化
const initAction = () => {
  generateSearchData();
};

// 检索数据
const onSearch = (filteredStudents: IStudent[]) => {
  searchStudentArr.value = filteredStudents;
};

// 保存学生信息
const onSave = (student: IStudent) => {
  if (modelInfo.value.type === 'add') {
    // 添加学生信息
    studentArr.push({
      ...student,
      create_at: getNowDateTime(),
      update_at: getNowDateTime()
    });
  } else {
    // 修改学生信息
    const index = studentArr.findIndex((i) => i.id === student.id);
    if (index !== -1) {
      studentArr[index] = {
        ...student,
        update_at: getNowDateTime()
      };
    }
  }
  generateSearchData();
  stusave();
  closeModel();
};

// 添加学生信息
const addStudent = () => {
  stuFormData.value = {
    id: '',
    age: '',
    email: '',
    gender: '',
    hobbies: '',
    name: '',
    phone: ''
  };
  modelInfo.value.type = 'add';
  modelInfo.value.title = '添加学生信息';
  isShowModel.value = true;
};

// 修改学生信息
const editStuInfo = (stu: IStudent) => {
  modelInfo.value.type = 'edit';
  modelInfo.value.title = '修改学生信息';
  stuFormData.value = cloneDeep(stu);
  isShowModel.value = true;
};

// 删除学生
const delStuInfo = (item: IStudent) => {
  const index = studentArr.findIndex((i) => i.id === item.id);
  if (index !== -1) {
    studentArr.splice(index, 1);
  }
  generateSearchData();
  changeSeletedItem();
  stusave();
};

// 删除选中学生
const delSelectedStudents = (selectedStudents: IStudent[]) => {
  selectedStudents.forEach((item) => {
    delStuInfo(item);
  });
};

// 关闭模态框
const closeModel = () => {
  isShowModel.value = false;
};

// 全选全不选
const changeSelectedAll = (event: Event) => {
  const checked = (event.target as HTMLInputElement).checked;
  searchStudentArr.value.forEach((item: IStudent) => {
    item.seleted = checked;
  });
};

// 修改全选全不选状态
const changeSeletedItem = () => {
  if (searchStudentArr.value.length > 0) {
    isAllSelected.value = searchStudentArr.value.every((i) => i.seleted);
  } else {
    isAllSelected.value = false;
  }
};

// 计算平均年龄
const avgAge = computed(() => {
  if (searchStudentArr.value.length === 0) return 0;
  const totalAge = searchStudentArr.value.reduce(
    (acc, curr) => acc + Number(curr.age),
    0
  );
  return Math.round(totalAge / searchStudentArr.value.length);
});

// 保存到localStorage
const stusave = () => {
  localStorage.setItem('student', JSON.stringify(studentArr));
};

// 生成搜索数据
const generateSearchData = () => {
  searchStudentArr.value = studentArr.filter((i) => i.name.includes(keyword.value));
};

// 初始化
onMounted(() => {
  initAction();
});
</script>

<style lang="scss" scoped>
@import './style/demo1.scss';
</style>